package com.async.controller;


import com.async.Hander.SyncStudentHandler;
import com.async.entity.Student;
import com.async.mapper.StudentMapper;
import com.async.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@Log4j
@AllArgsConstructor
@RequestMapping("/student/sync")
public class StudentController {


    private SyncStudentHandler syncStudentHandler;
    private StudentService studentService;
    private StudentMapper studentMapper;

    private DataSource dataSource;

    @GetMapping("/getDataSource")
    public String getDataSource() {
        System.out.println(dataSource);
        return "ok";
    }

    @GetMapping("/get1")
    public String selectStudents() {
        Long beginTime = System.currentTimeMillis();
//        List<Student> studentList= studentService.list(new QueryWrapper<Student>().last("limit 0,200000"));
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().last("limit 0,1000000"));
        Long endTime = System.currentTimeMillis();
        System.out.println("花费的时间是" + (endTime - beginTime));
        return "花费的时间是" + (endTime - beginTime) + ",学生数据大小为" + studentList.size();
    }


    @GetMapping("/get")
    public String syncSelectStudents() {
        Long beginTime = System.currentTimeMillis();
        //接收集合各段的 执行的返回结果
        List<Future<List<Student>>> futureList = new ArrayList<Future<List<Student>>>();
        int studentSize = studentMapper.getStudentSize();
        //多线程批量处理的数量
        int threadSize = 4;
//        int count=400000;
        int endSize = 250000;
        int start = 0;
        int end = 0;
        for (int i = 1; i <= threadSize; i++) {
            end = endSize * i - 1;
            if (i == threadSize) {
                end = studentSize + 1000;
            }
            //每段数据集合并行入库
            futureList.add(syncStudentHandler.syncSelectStudents(start, endSize, i));
            start = end + 1;
        }
        List<Student> studentList = new ArrayList<>();
        studentList = Collections.synchronizedList(studentList);
        //对各个线程段结果进行解析
        for (Future<List<Student>> future : futureList) {
            if (null != future) {
                try {
//                    System.out.println(future.get().size()+",当前数据量");
                    studentList.addAll(future.get());
                    log.info("current thread id =" + Thread.currentThread().getName() + ",result=");
                } catch (InterruptedException | ExecutionException e) {
                    log.info("线程运行异常！");
                }
            } else {
                log.info("线程运行异常！");
            }
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("花费的时间是" + (endTime - beginTime));
        return "花费的时间是" + (endTime - beginTime) + ",学生数组的大小是：" + studentList.size();
    }

    @GetMapping("/save1")
    public String saveStudents1() {
        List<String> stringList = new ArrayList<>();
        Long begin = System.currentTimeMillis();
        List<String> classList = new ArrayList<>();
        //插入一些班级id，用于下面随机获取
        classList.add("1437820983615537153");
        classList.add("1437821148237664258");
        classList.add("1437821215224971266");
        Random rand = new Random();
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Student student = new Student();
            student.setName(UUID.randomUUID().toString());
            student.setAge(18);
            student.setId(UUID.randomUUID().toString());
//            int randomId= rand.nextInt(3);
            //设置随机到的班级Id
//            student.setClassId(classList.get(randomId));
            students.add(student);
        }
        studentMapper.saveStudent(students);
        Long end = System.currentTimeMillis();
        System.out.println("所花的时间是:" + (end - begin));
        return "所花的时间是:" + (end - begin);
//        return stringList.toString();
    }


    @GetMapping("/save")
    public String saveStudents() {
        List<String> stringList = new ArrayList<>();
        Long begin = System.currentTimeMillis();
        List<String> classList = new ArrayList<>();
        //插入一些班级id，用于下面随机获取
//        classList.add("1437820983615537153");
////        classList.add("1437821148237664258");
////        classList.add("1437821215224971266");
        Random rand = new Random();
        List<Student> students = new ArrayList<>();
        List<Future<Boolean>> list = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Student student = new Student();
            student.setName(UUID.randomUUID().toString());
            student.setId(UUID.randomUUID().toString());
            student.setAge(18);
//            int randomId= rand.nextInt(3);
//            //设置随机到的班级Id
//            student.setClassId(classList.get(randomId));
            students.add(student);
        }

        //接收集合各段的 执行的返回结果
        List<Future<String>> futureList = new ArrayList<Future<String>>();
        //多线程批量处理的数量
//        int threadSize=5000;
        int threadCount = 10; //使用线程数量
        int endSize = students.size() / threadCount;
        int start = 0;
        int end = 0;
        for (int i = 0; i < threadCount; i++) {
            if (i == (threadCount - 1)) {
                end = students.size();
            } else {
                end = (i + 1) * endSize - 1;
            }
            List<Student> studentList = students.subList(start, end);
            start = end + 1;
            //每段数据集合并行入库
            futureList.add(syncStudentHandler.syncSaveStudents(studentList, i));
        }
        //对各个线程段结果进行解析
        for (Future<String> future : futureList) {
            String str;
            if (null != future) {
                try {
                    str = future.get().toString();
                    log.info("current thread id =" + Thread.currentThread().getName() + ",result=" + str);
                } catch (InterruptedException | ExecutionException e) {
                    log.info("线程运行异常！");
                }
            } else {
                log.info("线程运行异常！");
            }
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("所花的时间是:" + (endTime - begin));
        return "所花的时间是:" + (endTime - begin);
//        return stringList.toString();
    }


}
